package org.pim.smart.viewer.provider;

import java.util.Collections;
import java.util.List;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.pim.smart.hibernate.domain.ContactMain;
import org.pim.smart.hibernate.domain.GroupContact;
import org.pim.smart.service.ContactMainService;
import org.pim.smart.service.ContactMainServiceImpl;

public class ContactBookTreeViewerContentProvider implements
		ITreeContentProvider {
	
	@SuppressWarnings("unchecked")
	@Override
	public Object[] getElements(Object inputElement) {
		// TODO Auto-generated method stub
		if (inputElement instanceof List) {
			return ((List) inputElement).toArray();
		} else {
			return Collections.EMPTY_LIST.toArray();
		}
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		// TODO Auto-generated method stub

	}

	@Override
	public Object[] getChildren(Object parentElement) {
		// TODO Auto-generated method stub
		if (parentElement instanceof GroupContact){
			GroupContact group = (GroupContact)parentElement;
			ContactMainService contactSrv = new ContactMainServiceImpl();
			return contactSrv.getAllContactsByGroup(group).toArray();
		} else if (parentElement instanceof ContactMain){
			return Collections.EMPTY_LIST.toArray();
		} else {
			return Collections.EMPTY_LIST.toArray();
		}
	}

	@Override
	public Object getParent(Object element) {
		// TODO Auto-generated method stub
		if (element instanceof GroupContact){
			return null;
		} else if (element instanceof ContactMain){
			ContactMainService contactSrv = new ContactMainServiceImpl();
			GroupContact parent = contactSrv.getGroupOfContact(((ContactMain)element).getContactMainOid());
			contactSrv.releaseDataBaseResource();
			return parent;
		} else {
			return null;
		}
	}

	@Override
	public boolean hasChildren(Object element) {
		// TODO Auto-generated method stub
		if (element instanceof GroupContact){
			if (this.getChildren(element).length == 0){
				return false;
			} else {
				return true;
			}
		} else {
			return false;
		}
	}
}
